/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import DataAccess.DataAccessFacade;
import DomainModel.ManageEmail;
import DomainModel.ResetPassword;
import DomainModel.User;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Team2
 */
@WebServlet(name = "ChangePasswordController", urlPatterns = {"/ChangePasswordController"})
public class ChangePasswordController extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Map<String, String> messages = new HashMap<>();
        request.setAttribute("messages", messages);
        String strErrMsg = null;
        String token = request.getParameter("token");
        if (token != null) {
            try {
                ResetPassword passwordReset = DataAccessFacade.getInstance().getPasswordResetByToken(token);
                if (passwordReset != null && !passwordReset.isExpired()) {
                    request.setAttribute("token", token);
                    request.getRequestDispatcher("/changePassword.jsp").forward(request, response);
                } else {
                    strErrMsg = "Password reset token is invalid or expired. Please, try again.";
                    messages.put("error", strErrMsg);
                    request.getRequestDispatcher("/forgotPassword.jsp").forward(request, response);
                }
            } catch (Exception e) {
                strErrMsg = "Problem verifying password reset token. Please, generate a new token or try again, later.";
                messages.put("error", strErrMsg);
                request.getRequestDispatcher("/forgotPassword.jsp").forward(request, response);
            }
        } else {
            strErrMsg = "Invalid URL. Please, enter email and submit to reset password.";
            messages.put("error", strErrMsg);
            request.getRequestDispatcher("/forgotPassword.jsp").forward(request, response);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doChangePassword(request, response);
    }

    private void doChangePassword(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Prepare messages.
        Map<String, String> messages = new HashMap<>();
        request.setAttribute("messages", messages);

        String strPassword = request.getParameter("password");
        String strConfirmPassword = request.getParameter("confirmPassword");
        String token = request.getParameter("token");
        String message = null;

        try {
            if (strPassword.isEmpty() || strConfirmPassword.isEmpty()) {
                message = "Password and Confirm Password fields cannot not be empty.";
                messages.put("error", message);
                request.getRequestDispatcher("/changePassword.jsp").forward(request, response);
            } else if (!strPassword.equals(strConfirmPassword)) {
                message = "Password and Confirm Password values must match!";
                messages.put("error", message);
                request.getRequestDispatcher("/changePassword.jsp").forward(request, response);
            } else if (token == null) {
                message = "Unable to find password reset token or user in database!. Please request another!";
                messages.put("error", message);
                request.getRequestDispatcher("/forgotPassword.jsp").forward(request, response);
            } else {
                ResetPassword passwordReset = DataAccessFacade.getInstance().getPasswordResetByToken(token);
                if (passwordReset != null) {
                    if (!passwordReset.isExpired()) {

                        String validatePasswordResult = User.validatePassword(strPassword);
                        
                        if (!validatePasswordResult.isEmpty()) {
                            messages.put("error", validatePasswordResult);
                            request.getRequestDispatcher("/changePassword.jsp").forward(request, response);
                        } else {
                            DataAccessFacade.getInstance().changeUserPassword(passwordReset.getUserId(), strPassword);
                            DataAccessFacade.getInstance().deleteResetPasswordByToken(token);
                            message = "Password changed, successfuly. Please, login to use system.";
                            messages.put("success", message);
                            request.getRequestDispatcher("/login.jsp").forward(request, response);
                        }

                    } else {
                        message = "Password reset token is expired. Please request another!";
                        messages.put("error", message);
                        request.getRequestDispatcher("/forgotPassword.jsp").forward(request, response);
                    }

                }
            }
        } catch (Exception e) {
            message = "General error: " + e.getMessage();
            messages.put("error", message);
            request.getRequestDispatcher("/forgotPassword.jsp").forward(request, response);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Change Password";
    }// </editor-fold>
}
